package com.huluobo.a2308douyindemo.utils

import android.content.Context
import android.content.SharedPreferences

/**
 *  Created by LC on 2025/10/20.
 *  本地存储工具类,替代spUtils
 */
object MySp {
    private lateinit var sharedPreferences: SharedPreferences
    private lateinit var edit: SharedPreferences.Editor

    //1.获取sp  由于sp不是new出来的,是通过context中的getSharedPreferences 拿到的,所以封装的时候需要有提供一个context
    fun init(context: Context) {
        sharedPreferences = context.getSharedPreferences("mySp", Context.MODE_PRIVATE)
        //2.获取sp的编辑器
        edit = sharedPreferences.edit()
    }

    //存String值
    fun putString(key: String, value: String) {
        //3.提交内容,做出操作
        edit.putString(key, value)
        //4.提交
        edit.commit()
    }

    //取String值
    fun get(key: String): String {
        //通过sp取值,null是默认值,如果提供的key取不到对应的value,则提供一个null给返回
        return sharedPreferences.getString(key, "").toString()
    }

    //存布尔
    fun putBoolean(key: String, value: Boolean) {
        edit.putBoolean(key, value)
        edit.commit()
    }

    //取boolean
    fun getBoolean(key: String): Boolean {
        return sharedPreferences.getBoolean(key, false)
    }

    //存int
    fun putInt(key: String, value: Int) {
        edit.putInt(key, value)
        edit.commit()
    }

    fun getInt(key: String): Int {
        return sharedPreferences.getInt(key, 0)
    }

    //清空值
    fun remove(key: String) {
        edit.remove(key)
        //4.提交
        edit.commit()
    }
}